package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exceptions.LeaseException;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import kotlin.jvm.internal.Lambda;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SystemUserService systemUserService;
    @Override
    public CaptchaVo customCaptcha() {
        //先生成验证码图片和正确验证码
        /**
         * 参数1：130 图片宽度130像素
         * 参数2：48 图片高度48像素
         * 参数3：4 验证码位数4位
         */
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48,4);
        //验证码类型：数字字母混合
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //获取验证码图片
        //todo:base64是一种转码和解码的工具，可以将任何内容转成字符串
        //todo:1.怕乱码的字符串，转成base64 2.非字符串想要在json中携带，可以转成base64
        String imageStr=specCaptcha.toBase64();
        //获取正确的验证码
        String text=specCaptcha.text();
        //生成uuid
        String key = UUID.randomUUID().toString().replaceAll("-", "");
        //将uuid+正确验证码存储到redis｛有效期｝
        redisTemplate.opsForValue().set(key,text,300, TimeUnit.SECONDS);
        //验证码图片和uuid Vo->result.ok(vo)
        CaptchaVo captchaVo=new CaptchaVo(imageStr,key);
        return captchaVo;
    }

    @Override
    public String customlogin(LoginVo loginVo) {
        //1.验证码(验证码是否过期，是否正确)
        String redisCode = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if (ObjectUtils.isEmpty(redisCode)){
//            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED.getMessage(),ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED.getCode());
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //有意避免空指针问题
        if (!redisCode.equalsIgnoreCase(loginVo.getCaptchaCode())){
            //验证码错误
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //2.检查账号
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(lambdaQueryWrapper);
        if (systemUser==null){
            //账号错误
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //3.检查密码
        if (!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //4.账号是否可用
        if (systemUser.getStatus()== BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //5.生成token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;
    }
}
